import React, { useContext, useEffect, useState } from 'react';
import { Row, Col, Spin } from 'antd';
import { useBoolean, useRequest } from 'ahooks';
import PubSub from 'pubsub-js';
import request from '@/utils/request';
import Context from '@/pages/Transformer/context';
// eslint-disable-next-line import/no-named-default
import { default as SourceContext } from '@/pages/Transformer/components/SourcePanel/context';
// eslint-disable-next-line import/no-named-default
import { default as TargetContext } from '@/pages/Transformer/components/TargetPanel/targetContext';
import { serialize } from '@/pages/Transformer/components/TargetPanel/utils';
import SourcePanel from './components/SourcePanel';
import TargetPanel from './components/TargetPanel';

function getData(transformId, versionId) {
  return request.get(
    `/transform/queryVersionData?transformId=${transformId}&versionId=${versionId}`
  );
}

function Main() {
  const {
    state: { transformId, versionId, previewMode },
    dispatch,
  } = useContext(Context);
  const { dispatch: Sdispatch } = useContext(SourceContext);
  const { dispatch: Tdispatch } = useContext(TargetContext);
  const [mask, { setFalse: hideMask, setTrue: showMask }] = useBoolean();

  const { loading, run } = useRequest(() => getData(transformId, versionId), {
    // manual: true,
    onSuccess: response => {
      const { sourceTree, targetTree, sourceFormat, targetFormat, sourceMessage } = response;

      dispatch({
        type: 'update',
        payload: { versionId, sourceFormat, sourceMessage, targetFormat },
      });

      if (sourceTree) {
        Sdispatch({ type: 'set_the_whole_tree', payload: { data: serialize([sourceTree])[0] } });
      }

      if (targetTree) {
        Tdispatch({ type: 'set_the_whole_tree', payload: { data: serialize([targetTree], false)[0] } });
      }
    },
  });

  return (
    <Spin spinning={loading || mask}>
      <Row gutter={8}>
        <Col span={previewMode ? 0 : 12}>
          <SourcePanel />
        </Col>
        <Col span={previewMode ? 24 : 12}>
          <TargetPanel hideMask={hideMask} showMask={showMask} reloadPage={run} />
        </Col>
      </Row>
    </Spin>
  );
}

export default Main;
